/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Client;

import java.io.IOException;
import java.net.*;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author manelv8
 */
public class ClientSocketUDP implements InterfaceClientSocket {

    byte[] receiveData = new byte[1024];
    byte[] sendData = new byte[1024];
    DatagramSocket clientUDP;
    InetAddress IPAddress;
    int porta;

    public ClientSocketUDP(String host, int porta) {
        try {
            clientUDP = new DatagramSocket();
            IPAddress = InetAddress.getByName(host);
            this.porta = porta;

        } catch (UnknownHostException ex) {
            Logger.getLogger(ClientSocketUDP.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SocketException ex) {
            Logger.getLogger(ClientSocketUDP.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public DatagramSocket getClientUDP() {
        return clientUDP;
    }

    public void setClientUDP(DatagramSocket clientUDP) {
        this.clientUDP = clientUDP;
    }
    
    

    @Override
    public void enviarMsg(String msg) {

        try {
            sendData = msg.getBytes();
            DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, porta);
            clientUDP.send(sendPacket);
        } catch (IOException ex) {
            Logger.getLogger(ClientSocketUDP.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    @Override
    public String receberMsg() {
       String recebido = "";
        try {
            
            DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
            clientUDP.receive(receivePacket);
            recebido = new String(receivePacket.getData());
            
        } catch (IOException ex) {
            Logger.getLogger(ClientSocketUDP.class.getName()).log(Level.SEVERE, null, ex);
        }
        return recebido;
    }

    @Override
    public String conectar() {
        String retorno = "";
        enviarMsg("abrindo_conexao");
        retorno = receberMsg();
        return retorno;
    }

    @Override
    public void fechar() {
       clientUDP.close();
    }
}
